<?php

namespace app\runman\controller;

use app\common\model\OpinionFeedback;
use app\common\validate\Upload;
use app\common\controller\Base;
use think\Request;
use app\common\lib\Util;

class User extends Base
{
    protected $request;

    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    //提交反馈
    public function feedback(Upload $validate, OpinionFeedback $feedback)
    {
        $opinion = $this->request->param('opinion');
        $imgUrl = $this->request->file('img_url');
        if (empty($opinion) && $opinion != '0') {
            return Util::apiResponse([], '反馈内容不能为空', 400);
        }
        $url = [];
        if ($imgUrl) {
            $uploadPath = './upload/runman/feedback/';
            if (!is_dir($uploadPath)) {
                mkdir($uploadPath, 0777, true);
            }
            //多图,单图
            if (is_array($imgUrl)) {
                foreach ($imgUrl as $k => $v) {
                    $data = array(
                        'image' => $v
                    );
                    $res = $validate->check($data);
                    if (!$res) {
                        return Util::apiResponse([], $validate->getError(), 400);
                    }
                    $info = $v->move($uploadPath);
                    if (!$info) {
                        return Util::apiResponse([], '上传失败', 400);
                    }
                    $url[] = $uploadPath . str_replace('\\', '/', $info->getSaveName());
                }
            } else {
                $data = array(
                    'image' => $imgUrl
                );
                $res = $validate->check($data);
                if (!$res) {
                    return Util::apiResponse([], $validate->getError(), 400);
                }
                $info = $imgUrl->move($uploadPath);
                if (!$info) {
                    return Util::apiResponse([], '上传失败', 400);
                }
                $url[] = $uploadPath . str_replace('\\', '/', $info->getSaveName());
            }
        }
        $opinionData = ['opinion' => $opinion,
            'img_url' => json_encode($url),
            'user_id' => $this->userId,
            'back_type' => $feedback::RUNMAN_BACK
        ];
        $feedback->save($opinionData);
        return Util::apiResponse([], '', 200);
    }
}
